package dao

import (
	"github.com/jinzhu/gorm"
	"pojo/model"
)

// 分类数据库访问
type CategoryDao struct {
	db *gorm.DB
}

func NewCategoryDao(db *gorm.DB) *CategoryDao {

	return &CategoryDao{
		db: db,
	}
}

// 保存分类信息
func (this *CategoryDao) InsertCategory(category *model.Category) (int64, error) {
	result := this.db.Save(category)
	return result.RowsAffected, result.Error
}

// 修改分类信息
func (this *CategoryDao) UpdateCategory(category *model.Category) (int64, error) {
	result := this.db.Save(category)
	return result.RowsAffected, result.Error
}

// 查询分类信息
func (this *CategoryDao) ListCategory(pid uint64) ([]*model.Category, error) {

	categories := make([]*model.Category, 0)

	err := this.db.Where("pid = ?", pid).Find(&categories).Error

	return categories, err
}

// 删除分类信息
func (this *CategoryDao) DeleteCategory(id uint64) (error) {

	result := this.db.Where("id = ?", id).Delete(&model.Category{})

	return result.Error
}

// 根据ID查询分类信息
func (this *CategoryDao) FindCategory(id uint64) (*model.Category, error) {

	category := &model.Category{}

	result := this.db.Where("id = ?", id).Find(category)

	return category, result.Error
}
